import dao.StudentDao;
import dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import pojo.Student;
import pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.List;


public class Demo {

    SqlSessionFactory sessionFactory;
    SqlSession session;
    @Before
    public void config() {
//        类加载器获取文件流
        InputStream in=null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");

        } catch (IOException e) {
            e.printStackTrace();
        }
//构建者1模式创建SqlSessionFactory对象
        sessionFactory = new SqlSessionFactoryBuilder().build(in);
    }
    @Test
public void testFindAll() {
//    获取sqlSession对对象
         session = sessionFactory.openSession();
        UserDao userDao = session.getMapper(UserDao.class);
        List<User> all = userDao.findAll();
        for (User user1 : all) {
            System.out.println(user1);
        }
    }
    @Test
    public void testAdd(){
        session = sessionFactory.openSession();
        UserDao userDao = session.getMapper(UserDao.class);
        User user = new User();
        user.setName("赵四");
        user.setPassword("123");
        user.setSex("男");
        user.setBirthday(new java.util.Date());
        user.setRegisterTime(new java.util.Date());
        userDao.add(user);
    }
    @Test
    public void testUpDate(){
        session = sessionFactory.openSession();
        UserDao userDao = session.getMapper(UserDao.class);
        User user = new User();
        user.setId(3);
        user.setName("赵六");
        user.setPassword("123");
        user.setSex("男");
        user.setBirthday(new java.util.Date());
        user.setRegisterTime(new java.util.Date());
        int update = userDao.update(user);

    }
    @Test
    public void testDelete() {
        session = sessionFactory.openSession();
        UserDao userDao = session.getMapper(UserDao.class);
        boolean delete = userDao.delete(2);
        System.out.println(delete);
    }
@Test
public void testInsert(){
    session = sessionFactory.openSession();
    StudentDao student1 = session.getMapper(StudentDao.class);

    Student student = new Student();
    student.setName("无奈三");
    student1.insert(student);
}


    @After
    public void testClose() {
        session.commit();
        session.close();
    }
}
